/**
 * Base graphic device use for all the application
 */

/**
 * global context using every where in all application
 */
var gl;

slContext = function()
{
	// view width and height
	this.width 			= 0;
	this.height 		= 0;
	
	this.view			= null;
	this.projection		= null;
	
	//call back
	this.drawfunc 		= null;
	this.keyfunc		= null;
	this.updatefunc		= null;
	
	//context
	this.gl				= null;
	
	//frame time
	this.elapsedTime	= 0;
	this.frameTime		= 0;
};


var last_time = 0;
function slMainLoopCallback( context )
{
	 if ( context.updatefunc != null)
	    {
	        var cur_time = new Date().getTime();
	        if (last_time != 0)
	        {
	            var elapsedTime = cur_time - last_time;
	            context.elapsedTime = elapsedTime;
	            context.frameTime 	= cur_time;
	            context.updatefunc( context, elapsedTime );
	        }
	        last_time = cur_time;
	    }

	    if ( context.keyfunc != null )
	    {
	    	context.keyfunc( context );
	    }

	    if ( context.drawfunc != null )
	    {
	    	context.drawfunc( context );
	    }
}

function slInitContext( context, canvas, atrribute )
{
	try
	{
		if( atrribute == null )
			{
				context.gl = canvas.getContext("experimental-webgl");
			}
		else
			context.gl = canvas.getContext("experimental-webgl", attribute );
	} catch(e)
	{
		
	}
	
	if( context.gl == null )
	{
		alert('WebGL initialization failed.  Please make sure your browser supports WebGL.');
	}
	
	context.width		= canvas.width;
	context.height		= canvas.height;
	context.view 		= new slMatrix();
	context.projection	= new slMatrix();

	gl = context.gl;
}

function slMainLoop( context )
{
	setInterval ( function(){ slMainLoopCallback (context); }, 15 );
}

function slRegisterDrawFunc( context, drawfunc )
{
	context.drawfunc = drawfunc;
}

function slRegisterKeyFunc( context, keyfunc )
{
	context.keyfunc = keyfunc;
}

function slRegisterUpateFunc( context, updatafunc )
{
	context.updatefunc = updatafunc;
}

function slLogMessage( msg )
{
	console.log( msg );
}


